package org.calrissian.restdoclet.model.type.property;

import com.sun.javadoc.FieldDoc;
import com.sun.javadoc.RootDoc;
import com.sun.javadoc.Type;
import org.calrissian.restdoclet.model.Model;
import org.calrissian.restdoclet.model.ModelProperty;
import org.calrissian.restdoclet.model.ModelRef;
import org.calrissian.restdoclet.model.type.ParamTypeInfo;
import org.calrissian.restdoclet.model.type.ParamTypeInfos;

import java.util.Map;

import static org.calrissian.restdoclet.util.TypeUtils.*;

/**
 * 这时数组（List）字段的处理器
 * Created by admin on 2017/9/3.
 */
public class ArrayModelPropertyGentor extends ModelPropertyGenerator{

    @Override
    public boolean belongToThisGenerator(Type fieldType, Type ownerType) {
        if(dataType(fieldType).startsWith("array")) {
            return true;
        }
        return false;
    }

    @Override
    public ModelProperty generate(Type fieldType, FieldDoc fieldDoc, Type ownerType, Map<String, Model> result, RootDoc rootDoc, ParamTypeInfos paramTypeInfos) {

        ModelProperty modelProperty = getBaseModelProperty(fieldType, fieldDoc);

        Type fieldItemType;
        if(fieldType.getElementType() != null) {
            fieldItemType = fieldType.getElementType();
        } else {
            fieldItemType = fieldType.asParameterizedType().typeArguments()[0];
        }

        ParamTypeInfo paramTypeInfo = paramTypeInfos.get(ownerType.toString());
        if(paramTypeInfo != null && paramTypeInfo.getParamType(fieldItemType.qualifiedTypeName())!=null) {
            fieldItemType = paramTypeInfo.getParamType(fieldItemType.qualifiedTypeName());
        }
        ModelRef fieldModelRef = new ModelRef();
        fieldModelRef.setType(getTypeName(fieldItemType));
        modelProperty.setItems(fieldModelRef);
        if (needLoad(fieldItemType)
                && !result.containsKey(dataType(fieldItemType))) {
            result.putAll(getModel(result, fieldItemType, rootDoc, getAllParamTypeInfos(fieldItemType, paramTypeInfos)));
        }

        return modelProperty;
    }
}
